import React, { Fragment } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import BraftEditor from 'braft-editor';
import {
    Form,
    Button,
    Input,
    DatePicker,
    TreeSelect,
    // Upload,
    // Icon,
    message,
    Modal
} from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import { get as getPath } from 'object-path';
import 'braft-editor/dist/index.css';
import moment from 'moment';
import { formatMessage } from 'umi';
// import Debounce from 'lodash-decorators/debounce';
// import Bind from 'lodash-decorators/bind';
// import BizIcon from '@/components/BizIcon';
// import UploadDraggerAws from '@/components/UploadDraggerAws';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import style from './RulesDetail.less';
// 不允许添加尺寸大于100M的文件
const myValidateFn = file => {
    if (file.size > 1024 * 1024 * 100) {
        message.error('Size is greater than 1M!');
        return false;
    }
    return true;
};
class RulesAdd extends React.Component {
    state = {
        // allFileList: [],
        // uploadResourceFile: null,
        editorState: getPath(this.props, 'value'),
        recvCompanyTree: []
        // mystatus: true // 用来判断文件上传状态，暂时弃用
    };

    componentDidMount() {
        const { dispatch } = this.props;
        // 获取公司树
        dispatch({
            type: 'rules/fetchCompanyTree',
            payload: {
                companyId: '',
                permissionUrl: ''
            },
            callback: res => {
                if (res.code !== 10000) {
                    message.error(res.msg);
                }
            }
        });

        // 编辑-获取详情
        if (
            getPath(this.props, 'location.query.ruleId') &&
            getPath(this.props, 'location.query.ruleId') !== 'undefined'
        ) {
            this.fetchDetail();
        } else {
            const params = {
                id: null,
                content: '',
                createUser: '',
                recvCompany: '',
                startTime: null,
                title: '',
                detail: null
                // resourceRelation: []
            };
            dispatch({
                type: 'rules/save',
                payload: {
                    changeData: params
                }
            });
        }
    }

    // 文件上传之前触发-文件大小、个数限制
    beforeUpload = info => {
        if (info.size > 1024 * 1024 * 100) {
            message.error(
                formatMessage({
                    id: 'edit.model.file.big'
                })
            );
            return false;
        }
        if (getPath(this.props, 'changeData.files') === 10) {
            Modal.error({
                title: `${formatMessage({
                    id: 'edit.model.file.num'
                })}`
            });
            return false;
        }
        return true;
    };

    // 获取详情
    fetchDetail = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'rules/fetchDetail',
            payload: {
                ruleId: getPath(this.props, 'location.query.ruleId')
            },
            callback: res => {
                const { form, rules } = this.props;
                const { changeData } = rules;
                if (res.code === 10000) {
                    // const fileList = [];
                    // const files = res.data.ruleFile ? res.data.ruleFile : [];
                    // files.forEach(item => {
                    //     const { originName, url, keyName } = item;
                    //     const fileObj = {
                    //         keyName,
                    //         name: originName,
                    //         url,
                    //         uid: keyName
                    //     };
                    //     fileList.push(fileObj);
                    // });
                    const trr = [];
                    if (res.data.recvCompany && res.data.recvCompany !== '') {
                        let theObj = null;
                        res.data.recvCompany.split(',').forEach((item, index) => {
                            theObj = {};
                            theObj.label = res.data.recvCompanyName.split(',')[index];
                            theObj.value = Number(item);
                            trr.push(theObj);
                        });
                    }
                    if (changeData.id) {
                        form.setFieldsValue({
                            detail: BraftEditor.createEditorState(`${changeData.detail}`)
                        });
                    } else {
                        form.setFieldsValue({
                            detail: BraftEditor.createEditorState(null)
                        });
                    }
                    this.setState({
                        // allFileList: fileList,
                        recvCompanyTree: trr
                    });
                } else {
                    message.error(res.msg);
                }
            }
        });
    };

    // 树选择器改变
    saveTree = value => {
        this.setState({ recvCompanyTree: value });
    };

    // 提交
    handleSubmit = e => {
        e.preventDefault();
        const { dispatch, form } = this.props;
        // const { mystatus } = this.state;
        form.validateFields((err, values) => {
            if (!err) {
                // const array = [];
                // if (getPath(this.state, 'uploadResourceFile')) {
                //     array.push(getPath(this.state, 'uploadResourceFile'));
                // }
                const choosecompany = [];
                values.recvCompany.forEach(element => {
                    choosecompany.push(element.value);
                });
                // if (!mystatus) {
                //     message.error(
                //         `${formatMessage({
                //             id: 'edit.message.fileStatus'
                //         })}`
                //     );
                //     return false;
                // }
                const nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
                const formTime = values.startTime.format('YYYY-MM-DD HH:mm:ss');
                const trueTime = moment(nowTime).isBefore(formTime);
                if (!trueTime) {
                    message.error(
                        `${formatMessage({
                            id: 'edit.message.trueTime'
                        })}`
                    );
                    return false;
                }
                const params = {
                    id: values.id ? values.id : null,
                    recvCompany: choosecompany,
                    startTime: values.startTime.format('YYYY-MM-DD HH:mm:ss'),
                    content: values.content,
                    title: values.title,
                    detail: values.detail.toHTML()
                    // resourceRelation: array
                };
                dispatch({
                    type: 'rules/fetchAdd',
                    payload: params,
                    callback: res => {
                        if (res.code === 10000) {
                            message.success(res.msg);
                            history.push('/office/info/notice/article/rules');
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
                return true;
            }
            return false;
        });
    };

    // 具体时间范围控制
    handleEndOpenChange = open => {
        const me = this;
        if (open) {
            me.currentTime = moment();
        }
        this.setState({ currentTime: moment() });
    };

    // 不可选择以前的时间
    disabledEndDate = currentDate => {
        const startValue = getPath(this.state, 'currentTime');
        if (!currentDate || !startValue) {
            return false;
        }
        return currentDate.valueOf() <= startValue.valueOf();
    };

    handleEditorChange = editorState => {
        this.setState({ editorState });
    };

    // 文件上传后触发
    changeAllFileList = (showFileList, uploadResource) => {
        // 遍历文件状态，如果有正在上传或报错则改变mystatus为false，当点击提交时禁止提交
        showFileList.forEach(item => {
            if (item.status === 'uploading' || item.status === 'error') {
                this.setState({
                    mystatus: false
                });
            } else {
                this.setState({
                    mystatus: true
                });
            }
        });
        this.setState({
            allFileList: showFileList,
            uploadResourceFile: uploadResource
        });
    };

    render() {
        // const { allFileList, uploadResourceFile } = this.state;
        const {
            loading,
            rules: { changeData, companyTree }
        } = this.props;
        const {
            form: { getFieldDecorator }
        } = this.props;
        const formItemLayout = {
            labelCol: {
                sm: { span: 24 },
                md: { span: 3 }
            },
            wrapperCol: {
                sm: { span: 24 },
                md: { span: 9 }
            }
        };
        const getTreeData = (data, fieldsName = { value: 'id', title: 'companyName' }) =>
            data.map(item => ({
                ...item,
                value: item[fieldsName.value],
                title: item[fieldsName.title],
                key: item[fieldsName.value],
                children: item.children ? getTreeData(item.children, fieldsName) : item.children
            }));
        // const { TreeNode } = TreeSelect;
        const dateFormat = ['YYYY-MM-DD-dddd HH:mm:ss'];
        const controls = [
            'undo',
            'redo',
            'separator',
            'font-size',
            'line-height',
            'letter-spacing',
            'separator',
            'text-color',
            'bold',
            'italic',
            'underline',
            'strike-through',
            'separator',
            'superscript',
            'subscript',
            'remove-styles',
            'emoji',
            'separator',
            'text-indent',
            'text-align',
            'separator',
            'headings',
            'list-ul',
            'list-ol',
            'blockquote',
            'code',
            'separator',
            'media',
            'link',
            'hr',
            'separator',
            'clear'
        ];
        return (
            <Fragment>
                <PageHeaderWrapper>
                    <div className={style.wncontainer}>
                        <Form {...formItemLayout} style={{ padding: 16 }}>
                            <Form.Item>
                                {getFieldDecorator('id', {
                                    initialValue: changeData.id
                                })(<Input hidden type="number" />)}
                            </Form.Item>
                            <Form.Item
                                label={formatMessage({
                                    id: 'edit.rulelabel.title'
                                })}
                                // extra={formatMessage({
                                //     id: 'edit.message.help'
                                // })}
                                // style={{ marginBottom: '10px' }}
                            >
                                {getFieldDecorator('title', {
                                    initialValue: changeData.title,
                                    rules: [
                                        {
                                            required: true,
                                            message: `${formatMessage({
                                                id: 'edit.message.ruletitle'
                                            })}`
                                        },
                                        {
                                            min: 2,
                                            max: 50,
                                            message: '请输入2-50个字符'
                                        }
                                    ]
                                })(
                                    <Input
                                        placeholder={formatMessage({
                                            id: 'edit.message.ruletitle'
                                        })}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item
                                label={formatMessage({
                                    id: 'edit.label.startTime'
                                })}
                            >
                                {getFieldDecorator('startTime', {
                                    initialValue: changeData.startTime
                                        ? moment(changeData.startTime, dateFormat)
                                        : null,
                                    rules: [
                                        {
                                            required: true,
                                            message: `${formatMessage({
                                                id: 'edit.message.startTime'
                                            })}`
                                        }
                                    ]
                                })(
                                    <DatePicker
                                        showTime={{
                                            defaultValue: moment(
                                                moment()
                                                    .add(2, 'minutes')
                                                    .format('HH:mm:ss'),
                                                'HH:mm:ss'
                                            )
                                        }}
                                        showToday={false}
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder={formatMessage({
                                            id: 'edit.message.startTime'
                                        })}
                                        disabledDate={this.disabledEndDate}
                                        onOpenChange={this.handleEndOpenChange}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item
                                label={formatMessage({
                                    id: 'edit.label.recvCompany'
                                })}
                            >
                                {getFieldDecorator('recvCompany', {
                                    initialValue: getPath(this.state, 'recvCompanyTree'),
                                    rules: [
                                        {
                                            required: true,
                                            message: `${formatMessage({
                                                id: 'edit.message.recvCompany'
                                            })}`
                                        }
                                    ]
                                })(
                                    <TreeSelect
                                        treeData={getTreeData(companyTree)}
                                        treeCheckable
                                        searchPlaceholder={formatMessage({
                                            id: 'edit.message.recvCompany'
                                        })}
                                        showCheckedStrategy={TreeSelect.SHOW_ALL}
                                        onChange={this.saveTree}
                                        treeCheckStrictly
                                        style={{ width: '100%' }}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item
                                label={formatMessage({
                                    id: 'edit.rulelabel.content'
                                })}
                                {...formItemLayout}
                            >
                                {getFieldDecorator('content', {
                                    initialValue: changeData.content,
                                    rules: [
                                        {
                                            required: true,
                                            message: `${formatMessage({
                                                id: 'edit.message.content'
                                            })}`
                                        },
                                        {
                                            min: 2,
                                            max: 200,
                                            message: `${formatMessage({
                                                id: 'edit.message.rulehelp'
                                            })}`
                                        }
                                    ]
                                })(<TextArea rows={4} style={{ marginTop: '4px' }} />)}
                            </Form.Item>
                            {/* <Form.Item
                                label={formatMessage({
                                    id: 'edit.label.files'
                                })}
                                {...formItemLayout}
                            >
                                {getFieldDecorator('resourceRelation', {
                                    rules: [
                                        {
                                            message: `${formatMessage({
                                                id:
                                                    'edit.message.resourceRelation'
                                            })}`
                                        }
                                    ]
                                })(
                                    <UploadDraggerAws
                                        uploadUrl="/api/resource/producePutPreSignUrls"
                                        checkFileSize={100}
                                        checkFileType="JPG,JPEG,BMP,GIF,PNG,DOC,DOCX,ppt,pptx,PDF,xls,xlsx,RAR,ZIP,txt,ai"
                                        sysCode="OA"
                                        businessCode="SysRule"
                                        categoryCode="ruleFile"
                                        fileList={allFileList}
                                        uploadResource={uploadResourceFile}
                                        setFileList={this.changeAllFileList}
                                    >
                                        <p className="ant-upload-drag-icon">
                                            <BizIcon type="oa_form_bnt_upload" />
                                        </p>
                                        <p
                                            className="ant-upload-text"
                                            style={{ fontSize: '14px' }}
                                        >
                                            {formatMessage({
                                                id: 'edit.label.filesTips'
                                            })}
                                        </p>
                                        <p
                                            className="ant-upload-hint"
                                            style={{
                                                fontSize: '12px'
                                            }}
                                        >
                                            {formatMessage({
                                                id: 'edit.label.filesTipss'
                                            })}
                                        </p>
                                    </UploadDraggerAws>
                                )}
                            </Form.Item> */}
                            <Form.Item
                                label={formatMessage({
                                    id: 'edit.rulelabel.detail'
                                })}
                                wrapperCol={{ md: { span: 16 } }}
                            >
                                {getFieldDecorator('detail', {
                                    rules: [
                                        {
                                            required: true,
                                            message: `${formatMessage({
                                                id: 'edit.message.detail'
                                            })}`,
                                            validator: (_, value, callback) => {
                                                if (value.isEmpty()) {
                                                    callback(
                                                        `${formatMessage({
                                                            id: 'edit.message.detail'
                                                        })}`
                                                    );
                                                } else {
                                                    callback();
                                                }
                                            }
                                        }
                                    ]
                                })(
                                    <BraftEditor
                                        onChange={this.handleEditorChange}
                                        media={{
                                            uploadFn: this.myUploadFn,
                                            validateFn: myValidateFn,
                                            onChange: this.fileChange,
                                            accepts: {
                                                image: 'image/png,image/jpeg,image/gif'
                                            }
                                        }}
                                        imageControls={[
                                            {
                                                onClick: () => {} // 指定控件点击后的回调，参数为当前图片的block对象
                                            },
                                            'size',
                                            'remove'
                                        ]}
                                        controls={controls}
                                        excludeControls={['fullscreen']}
                                        style={{
                                            border: '1px solid #d9d9d9',
                                            borderTopWidth: '1.02px',
                                            borderRadius: '4px',
                                            marginTop: '4px'
                                        }}
                                        className={style.paddingBraftEditor}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item
                                wrapperCol={{
                                    sm: { span: 24, offset: 0 },
                                    md: { span: 8, offset: 3 }
                                }}
                            >
                                <Button
                                    type="primary"
                                    disabled={loading.effects['rules/fetchAdd']}
                                    style={{ marginRight: 16 }}
                                    htmlType="submit"
                                    onClick={this.handleSubmit}
                                >
                                    {formatMessage({
                                        id: 'btn.form.submit'
                                    })}
                                </Button>
                                <Button onClick={() => history.push('/office/info/notice/article/rules')}>
                                    {formatMessage({
                                        id: 'btn.form.unsubmit'
                                    })}
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                </PageHeaderWrapper>
            </Fragment>
        );
    }
}
export default withRoutePage(
    connect(({ rules, loading }) => ({
        rules,
        loading
    }))(Form.create()(RulesAdd))
);
